<template>
	<div class="card filter">
	<el-card  shadow="hover" style="height: 100%;" body-style="height:100%; overflow:auto">
		<template #header>
			<div class="card-header">
				<div class="tree-h-flex">
					<div class="tree-h-left">
						<el-input :prefix-icon="Search" v-model="filterText" placeholder="字典类型名称" />
					</div>
					<div class="tree-h-right">
						<el-dropdown @command="handleCommand">
							<el-button style="margin-left: 8px; width: 34px">
								<el-icon class="el-icon--center">
									<more-filled />
								</el-icon>
							</el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item command="expandAll">全部展开</el-dropdown-item>
									<el-dropdown-item command="collapseAll">全部折叠</el-dropdown-item>
									<el-dropdown-item command="rootNode">根节点</el-dropdown-item>
									<el-dropdown-item command="refresh">刷新</el-dropdown-item>
                                    <el-dropdown-item command="edit" v-auth="'system:dictData:add'">编辑</el-dropdown-item>                                    
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</div>
				</div>
			</div>
		</template>
        <div v-if="state.showButton" style="margin-bottom: 10px">
            <el-button size="small" type="success" class="ml10" @click="openDictType('add',null)">
                <el-icon><ele-CirclePlus /></el-icon>新增字典							
            </el-button>
            <el-button @click="cancelEdit" size="small">取消编辑</el-button>
        </div> 
		<div style="margin-bottom: 45px" v-loading="state.loading">                      
			<el-tree
				ref="treeRef"
				class="filter-tree"
				:data="state.dictTypeData"
				node-key="id"
				:props="{ children: 'children', label: 'name' }"
				:filter-node-method="filterNode"
				@node-click="nodeClick"
				highlight-current
				check-strictly               
			>
                <template #default="{node,data}">                   
                  <span class="enumText" >{{ data.name }}</span>                                    
                  <div class="buttons-container" v-if="state.showButton">
                    <span @click.stop="openDictType('add',node)">
                        <el-icon color="#409eff" >
						<ele-CirclePlus/>
					</el-icon>
                    </span>
                    <span @click.stop="openDictType('edit',node)">
                        <el-icon color="#409eff">
						<ele-EditPen/>
					</el-icon>
                    </span>
                    <span @click.stop="deleteDictType(node)">
                        <el-icon color="#409eff">
						<ele-Delete/>
					</el-icon>
                    </span>                    
                  </div>                                      
                </template>
        </el-tree>			
		</div>
	</el-card>
	</div>
    <EditDictType ref="editDictTypeRef" @refresh="initTreeData"/>
</template>

<script lang="ts" setup name="dictTypeTree">
import { onMounted, reactive, ref, watch,defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus';
import { Search, MoreFilled } from '@element-plus/icons-vue';
import { feature } from '/@/utils/axios-utils';
import { SysDictType } from '/@/api-services/models/system';
import dictTypeApi from '/@/api-services/apis/system/dictTypeApi';
// 引入组件
const EditDictType = defineAsyncComponent(() => import('./editDictType.vue'));

const filterText = ref('');
const editDictTypeRef=ref();
const treeRef = ref<InstanceType<typeof ElTree>>();
const state = reactive({
	loading: false,
	dictTypeData: [] as Array<SysDictType>,
	isShowCheckbox: false,
    showButton:false
});

// 与父组件的交互逻辑
const emits = defineEmits(['node-click','backType']);

onMounted(() => {
	initTreeData()	
});
const nodeClick = (node: any) => {
	emits('node-click', { id: node.id, name: node.name });
};

watch(filterText, (val) => {
	treeRef.value!.filter(val);
});

const openDictType=(type:string,node:any)=>{
    var dictType:any
    if(node==null){
        dictType=null
    }
    else{
        dictType=node.data;
        if(type==='add'){//如果是新增，传递当前节点Id作为parentId
            dictType={parentId:dictType.id}        
        }  
    }    
    editDictTypeRef.value.openDialog(type,dictType,state.dictTypeData)
}

const deleteDictType=(node:any)=>{
    var dictType=node.data;
    ElMessageBox.confirm(`此操作将永久删除字典类型【${dictType.name}】, 是否继续?`, '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			const [err]=await feature(dictTypeApi.delete({id:dictType.id }));
			if(err){
				ElMessage.error(err.message)
			}
			else{
				ElMessage.success('删除成功');
				initTreeData();
			}
		})
		.catch(() => {});
}
const initTreeData = async () => {
	state.loading = true;
	var res = await dictTypeApi.getDictTypeTree();
	state.dictTypeData = res.data.data ?? [];
	state.loading = false;
	//向父组件传递组织数据
	emits('backType',state.dictTypeData)	
};


const filterNode = (value: string, data: any) => {
	if (!value) return true;	
	return data.name.includes(value);
};

const handleCommand = async (command: string | number | object) => {
	if ('expandAll' == command) {
		for (let i = 0; i < treeRef.value!.store._getAllNodes().length; i++) {
			treeRef.value!.store._getAllNodes()[i].expanded = true;
		}
	} else if ('collapseAll' == command) {
		collapseAll();
	} else if ('refresh' == command) {
		initTreeData();
	} else if ('rootNode' == command) {
		emits('node-click', { id: 0});
	}
    else if('edit'==command){
        state.showButton=true;
    }
};
const cancelEdit=()=>{
    state.showButton=false;
}
const collapseAll=()=>{
    for (let i = 0; i < treeRef.value!.store._getAllNodes().length; i++) {
			treeRef.value!.store._getAllNodes()[i].expanded = false;
		}
}
// 导出对象
defineExpose({ initTreeData,collapseAll});
</script>

<style lang="scss" scoped>
.tree-h-flex {
	display: flex;
}

.tree-h-left {
	flex: 1;
	width: 100%;
}

.tree-h-right {
	width: 42px;
	min-width: 42px;
}
.filter-tree{
	padding-bottom: 8px;
	margin-bottom: 8px;	
	font-size: 14px;
	margin-bottom:5px
}
.buttons-container{
    margin-left: auto;
}
.buttons-container span{
    margin-left: 10px;
    padding-right: 5px;
}
.filter {
	box-sizing: border-box;
	width: 280px;
	padding: 0px;
	margin-right: 10px;
	.title {
		margin: 0 0 15px;
		font-size: 18px;
		font-weight: bold;
		color: var(--el-color-info-dark-2);
		letter-spacing: 0.5px;
	}
	.el-input {
		margin: 0 0 10px;
		width: 150px;
	}
	.el-scrollbar {
		:deep(.el-tree) {
			height: 80%;
			overflow: auto;
			.el-tree-node__content {
				height: 33px;
			}
		}
		:deep(.el-tree--highlight-current) {
			.el-tree-node.is-current > .el-tree-node__content {
				background-color: var(--el-color-primary);
				.el-tree-node__label,
				.el-tree-node__expand-icon {
					color: white;
				}
				.is-leaf {
					color: transparent;
				}
			}
		}
	}
}
</style>
